package com.macro.mall.portal.component.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson.JSON;
import com.macro.mall.portal.domain.bo.WxBO;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author yelong.xie
 * @date 2024/7/3 18:38
 */
@Component
@Slf4j
public class WxClient {
    @Autowired
    private WxMaService wxMaService;

    /**
     * 一个jscode只能用一次
     * {"openid":"odpJZ5eKn40O3bgOmtMe_HoUnBjo","sessionKey":"n8pOpJHAlJzN8ALpiKMAeQ=="}
     * {"errcode":40163,"errmsg":"code been used, rid: 66852c1a-130e6576-13027817"}
     *
     * @throws Exception
     */
    public WxBO getSessionInfo(String jsCode) {
        WxBO wxBO = new WxBO();
        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(jsCode);
            wxBO.setSessionKey(sessionInfo.getSessionKey());
            wxBO.setUnionid(sessionInfo.getUnionid());
            wxBO.setOpenid(sessionInfo.getOpenid());
        } catch (Exception e) {
            wxBO.setSuccess(Boolean.FALSE);
            wxBO.setErrorMsg(e.getMessage());
            log.error("com.macro.mall.portal.component.wx.WxClient#getSessionInfo error: {}", e.getMessage());
        }
        return wxBO;
    }

    /**
     * 获取用户id
     * @param code
     * @return
     */
    public WxBO getUserPhone(String code) {
        WxBO wxBO = new WxBO();
        try {
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(code);
            wxBO.setPurePhone(phoneNoInfo.getPurePhoneNumber());
        } catch (Exception e) {
            wxBO.setSuccess(Boolean.FALSE);
            wxBO.setErrorMsg(e.getMessage());
            log.error("com.macro.mall.portal.component.wx.WxClient#getUserPhone error: {}", e.getMessage());
        }
        return wxBO;
    }
}
